<template>
    <div id="mapContainer" class="mapContainer">
        <div
            style="position: absolute; top: 0; right: 0; z-index: 999; padding: 10px; border-radius: 4px; box-shadow: 0 2px 8px rgba(0,0,0,0.1);">

            <el-form>
                <el-form-item>
                    <el-select v-model="form.layer" style="width: 200px;">
                        <el-option v-for="item in layerList" :key="item.name" :label="item.name" :value="item.name" />
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="submitForm(formRef)">确定</el-button>
                    <el-button @click="queryDraw('Rectangle')">矩形</el-button>

                </el-form-item>
            </el-form>

        </div>
    </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import Map from '@/map/index';
import jsonData from './新疆维吾尔自治区.json'; //遮罩层数据
// import { weatherPointList } from '@/test/test.js';
import dmgis from '@/map/dmgis.js';
import ImageLayer from 'ol/layer/Image';

let olMap = ref(); //定义地图实例

onMounted(() => {
    olMap.value = new Map('mapContainer');
    const obj = olMap.value.layer.initLayer(); //初始化底图
    obj.layer.forEach((layer) => {
        const name = layer.get("layerName")
        if (name === '影像图层组') {
            layer.setVisible(true)
        } else {
            layer.setVisible(false)
        }
    })
    let extent = olMap.value.layer.initMaskLayer(jsonData); //添加遮罩层,并将范围全局化
    olMap.value.layer.fitExtentPadding({
        extent: extent
    }); //跳转到遮罩层

    addTile();//添加瓦片
    // addPrj(); //初始化工程
});
let dmProjectLayer;
let layerList = ref([]);
let getPrjImgParam; //获取工程图片参数
const addTile = () => {
    dmProjectLayer = new dmgis.olmap.ServiceLayer('xjczt', '/dmgis', {
        minZoom: 1,
        tileSize: [256, 256]
    });
    //获取工程的所有图层
    dmProjectLayer.InitService().then((res) => {
        layerList.value = res.RESPONSE.SERVER.LAYER;
        console.log("layerList.value:", layerList.value);
    });
};
let layerName;
let form = reactive({
    layer: ''
});
let tableData = ref([]); //工程表格数据
let sqlVal = ''; //存储sql语句
//提交表单，查询
const submitForm = (formEl, sql) => {
    sqlVal = sql; //sql语句保存方便修改添加后重新查询
    query(sql);

};
let temporaryPolygonArr = []; //用于编辑后决定进行哪种类型的查询
const query = (sql) => {
    //查询参数构建
    let getfeaturePoint = dmProjectLayer.GetFeatureMapService();

    // getfeaturePoint.type = "1"//索引
    // getfeaturePoint.strlist = "1,2,3,4"

    // getfeaturePoint.type = "2"//实体号
    // getfeaturePoint.strlist = "1,2,3,4"

    getfeaturePoint.type = '0'; //条件
    getfeaturePoint.strlayername = form.layer;
    getfeaturePoint.sql.strSql = sql && sql.length ? sql : 'dmgis_id > 0';

    // var rect = new dmgis.object.Envelope();
    // rect.minx
    // getfeaturePoint.sql.env  = rect;//矩形
    // getfeaturePoint.sql.strPos = "";//多边形

    dmProjectLayer.SendFeatureMapService(getfeaturePoint).then((res) => {
        if (res) {
            ElMessage.success('查询成功');
            layerName = form.layer; //存放当前表格的图层名
            //请求与表格结果对应的工程图片
            getPrjImgParam = {
                name: 'QUERY',
                singleLabel: true,
                attributes: {
                    where: sql && sql.length ? sql : 'dmgis_id > 0'
                }
            };
            addDmProject();

            //两种情况，返回结果为对象则转为数组用来渲染表格
            if (!Object.hasOwn(res.RESPONSE.FEATURES, 'FEATURE') && res.RESPONSE.FEATURES) {
                tableData.value = [];
            } else if (res.RESPONSE.FEATURES.FEATURE.length) {
                tableData.value = res.RESPONSE.FEATURES.FEATURE;
            } else {
                tableData.value = [res.RESPONSE.FEATURES.FEATURE];
            }
            // console.log(tableData.value);
        } else {
            ElMessage.error('查询失败');
        }
    });
};
let moveEndListener; // 用于保存事件监听器的引用
let serviceLayer; //工程图层
let isMoveEndBound = false; // 标记是否已绑定
//加载工程图片
const addDmProject = () => {
    if (olMap.value.layer.getLayerByName('工程图片图层')) {
        olMap.value.map.removeLayer(olMap.value.layer.getLayerByName('工程图片图层'));
    }

    dmProjectLayer.serviceLayer = new ImageLayer();
    dmProjectLayer.serviceLayer.setZIndex(2);

    serviceLayer = dmProjectLayer.serviceLayer;
    serviceLayer.set('layerName', '工程图片图层');

    let imgSvrParam = dmProjectLayer.ImgMapService;

    let extent = olMap.value.map.getView().calculateExtent(olMap.value.map.getSize());
    let size = olMap.value.map.getSize();
    //填参
    imgSvrParam.DispRect.minx = extent[0];
    imgSvrParam.DispRect.miny = extent[1];
    imgSvrParam.DispRect.maxx = extent[2];
    imgSvrParam.DispRect.maxy = extent[3];
    imgSvrParam.imgWid = size[0];
    imgSvrParam.imgHig = size[1];

    let param = {
        name: 'DMGISXML',
        version: '1.1',
        children: {
            name: 'REQUEST',
            children: {
                name: 'GET_IMAGE',
                attributes: {
                    minx: extent[0],
                    miny: extent[1],
                    maxx: extent[2],
                    maxy: extent[3],
                    width: size[0],
                    height: size[1],
                    bclr: '255,255,255',
                    disp: '0'
                },
                children: {
                    name: 'LAYERLIST',
                    children: {
                        name: 'LAYERDEF',
                        attributes: {
                            name: layerName,
                            visible: 1
                        },
                        // children: {
                        //     name: 'DISPHIGH',
                        //     attributes: {
                        //         type: 0,
                        //         objtype: 0
                        //     },
                        children: getPrjImgParam
                        // }
                    }
                }
            }
        }
    };

    //通过RefreshMap动态获取工程图片，实现地图的刷新
    dmProjectLayer.RefreshMap(serviceLayer, dmProjectLayer.ImgMapService, param, olMap.value.map.getView().getZoom());
    olMap.value.map.addLayer(serviceLayer);

    // 保存事件监听器的引用
    moveEndListener = function (evt) {
        let frameState = evt.frameState;
        // 填参
        imgSvrParam.DispRect.minx = frameState.extent[0];
        imgSvrParam.DispRect.miny = frameState.extent[1];
        imgSvrParam.DispRect.maxx = frameState.extent[2];
        imgSvrParam.DispRect.maxy = frameState.extent[3];
        imgSvrParam.imgWid = frameState.size[0];
        imgSvrParam.imgHig = frameState.size[1];

        let param = {
            name: 'DMGISXML',
            version: '1.1',
            children: {
                name: 'REQUEST',
                children: {
                    name: 'GET_IMAGE',
                    attributes: {
                        minx: frameState.extent[0],
                        miny: frameState.extent[1],
                        maxx: frameState.extent[2],
                        maxy: frameState.extent[3],
                        width: frameState.size[0],
                        height: frameState.size[1],
                        bclr: '255,255,255',
                        disp: '0'
                    },
                    children: {
                        name: 'LAYERLIST',
                        children: {
                            name: 'LAYERDEF',
                            attributes: {
                                name: layerName,
                                visible: 1
                            },
                            // children: {
                            //     name: 'DISPHIGH',
                            //     attributes: {
                            //         type: 0,
                            //         objtype: 0
                            //     },
                            children: getPrjImgParam
                            // }
                        }
                    }
                }
            }
        };
        dmProjectLayer.RefreshMap(serviceLayer, imgSvrParam, param, frameState.viewState.zoom);
    };

    //第一次添加moveend事件
    if (!isMoveEndBound) {
        olMap.value.map.on('moveend', moveEndListener);
        isMoveEndBound = true;
    }
};
let pointArr = ref([]); //存放点坐标
const queryDraw = (type) => {
    olMap.value.draw.startDrawing(type, false, (coordinates) => {
        pointArr.value = coordinates;
        bufferQuery(formatCoordinates(pointArr.value));
    });
}

const bufferQuery = (coordinates) => {
    if (!form.layer) {
        ElMessage.warning('请选择图层');
        return false;
    }
    temporaryPolygonArr = coordinates;
    //查询参数构建
    let getfeaturePoint = dmProjectLayer.GetFeatureMapService();

    getfeaturePoint.type = '0'; //条件
    getfeaturePoint.strlayername = form.layer;
    getfeaturePoint.sql.strPos = coordinates; //多边形

    dmProjectLayer.SendFeatureMapService(getfeaturePoint).then((res) => {
        if (res) {
            ElMessage.success('查询成功');

            layerName = form.layer; //存放当前表格的图层名
            //请求与表格结果对应的工程图片
            getPrjImgParam = {
                name: 'POLYGON',
                singleLabel: true,
                attributes: {
                    coords: coordinates
                }
            };
            addDmProject();

            //两种情况，返回结果为对象则转为数组用来渲染表格
            if (!Object.hasOwn(res.RESPONSE.FEATURES, 'FEATURE') && res.RESPONSE.FEATURES) {
                tableData.value = [];
            } else if (res.RESPONSE.FEATURES.FEATURE.length) {
                tableData.value = res.RESPONSE.FEATURES.FEATURE;
            } else {
                tableData.value = [res.RESPONSE.FEATURES.FEATURE];
            }
            // console.log(tableData.value);
        } else {
            ElMessage.error('查询失败');
        }
    });
};
function formatCoordinates(coords) {
    // 使用 map 遍历二维数组，将每组坐标转换为字符串
    const formatted = coords[0].map((pair) => pair.join(' '));
    // 使用 join 方法将所有字符串用分号分隔
    return formatted.join(';');
}
</script>

<style scoped>
.mapContainer {
    width: 100%;
    height: 91vh;
    position: relative;
}

button {
    padding: 8px 16px;
    background-color: #409eff;
    color: white;
    border: none;
    border-radius: 4px;
    cursor: pointer;
    font-size: 14px;
}

button:hover {
    background-color: #66b1ff;
}
</style>
